package com.blocks.gui;

import java.io.File;
import java.io.FileFilter;

import com.blocks.ScriptBlocksApplication;
import com.blocks.script.ScriptUtils;

import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.controls.ListBox;
import de.lessvoid.nifty.controls.TextField;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;

public class ExportScreenController implements ScreenController {
	private Nifty nifty;
	private Screen screen;
	private TextField textField;
	private ListBox listBoxImportScripts;
	
	@Override
	public void bind(Nifty nifty, Screen screen) {
		this.nifty = nifty;
		this.screen = screen;
		textField = screen.findNiftyControl("exportFileName", TextField.class);
		textField.setText(ScriptBlocksApplication.CONFIG_FILE);
		this.listBoxImportScripts = findListBoxControl("listBoxImportScripts");
		

		if (listBoxImportScripts != null) {
			File directory;
	        directory = new File(ScriptBlocksApplication.getInstance().getScriptDir()
	        		+ScriptBlocksApplication.CONFIG_FILE_FOLDER);
	        if(directory != null){
		        System.out.println("GET CONFIG FILES FROM PATH" + directory.getAbsolutePath());        
		        File[] fileArray = this.addAllFilesInDirectory(directory);
		        for(File file : fileArray){
		        	listBoxImportScripts.addItem(file.getName());
		        }
	        }
			
		}
	}

	@Override
	public void onEndScreen() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStartScreen() {
		// TODO Auto-generated method stub

	}
	
	public void backToMainMenu() {
		nifty.fromXml("Interfaces/niftytest.xml", "start");
	}
	public void save() {
		ScriptUtils.writeSceneToScript(textField.getText());
		//TODO make sure its ends in .js
		nifty.fromXml("Interfaces/niftytest.xml", "start");
	}
	
	private FileFilter getFileFilter() {
        return new FileFilter() {
            public boolean accept(File pathname) {
                return (pathname.getName().endsWith(".js"));
            }
        };
    }
    public  File[] addAllFilesInDirectory(File directory) {
    	try {
	        return directory.listFiles(getFileFilter());	        
        }catch (NullPointerException e){
        	e.printStackTrace();
        }
        return  null;
    }
	private ListBox findListBoxControl(final String id) {
		return screen.findNiftyControl(id, ListBox.class);
	}
}


